package com.jtcl.common.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class JacksonUtils {

    private static final ObjectMapper om;

    static {
        om = new ObjectMapper();
        om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static String writeValueAsString(Object obj) {
        try {
            return om.writeValueAsString(obj);
        } catch (Exception e) {
            log.error("json反序列化错误");
            return null;
        }
    }

    public static <T, K> T readValue(String content, Class<T> o1, Class<K> o2) {
        if (StringUtils.isEmpty(content)) {
            return null;
        }
        try {
            JavaType javaType = om.getTypeFactory().constructParametricType(o1, o2);
            return om.readValue(content, javaType);
        } catch (Exception e) {
            log.error("json反序列化错误", e);
            return null;
        }
    }

    public static <T> T readValue(String content, Class<T> o1) {
        if (StringUtils.isEmpty(content)) {
            return null;
        }
        try {
            return om.readValue(content, o1);
        } catch (Exception e) {
            log.error("json反序列化错误", e);
            return null;
        }
    }

    public static <T> List<T> readListValue(String value, Class<T> o1) {
        if (StringUtils.isEmpty(value)) {
            return null;
        }
        try {
            JavaType javaType = om.getTypeFactory().constructParametricType(ArrayList.class, o1);
            return om.readValue(value, javaType);
        } catch (Exception e) {
            log.error("json反序列化错误", e);
            return null;
        }
    }

    public static <T> T mapToObject(Map<?, ?> map, Class<T> clazz) {
        return om.convertValue(map, clazz);
    }

    public static <K, V> Map<K, V> objectToMap(Object o) {
        return om.convertValue(o, new TypeReference<Map<K, V>>() {});
    }
}
